package com.zwy.springecho;

import org.springframework.web.util.ContentCachingRequestWrapper;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

public class RequestUtils {

    public static String getCachedRequestBody(HttpServletRequest request) {
            try {
                if (request instanceof ContentCachingRequestWrapper) {
                    ContentCachingRequestWrapper wrappedRequest = (ContentCachingRequestWrapper) request;
                    byte[] contentAsByteArray = wrappedRequest.getContentAsByteArray();
                    return new String(contentAsByteArray, wrappedRequest.getCharacterEncoding());
                }
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
        return null;
    }

    public static String getRequestBody(ContentCachingRequestWrapper wrappedRequest) {
        try {
            // 获取字符流
            BufferedReader reader = wrappedRequest.getReader();
            // 使用 StringBuilder 来存储请求体内容
            StringBuilder requestBody = new StringBuilder();
            char[] buffer = new char[1024];
            int charsRead;

            // 读取请求体内容
            while ((charsRead = reader.read(buffer)) != -1) {
                requestBody.append(buffer, 0, charsRead);
            }
            // 返回请求体字符串
            return requestBody.toString();
        } catch (IOException e) {
            throw new RuntimeException("Failed to read request body", e);
        }
    }
}
